package com.star.generator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.baomidou.mybatisplus.generator.fill.Column;
import com.star.core.base.BaseController;

import java.sql.Types;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

/**
 * <p>
 * 代码生成
 * </p>
 * <pre>
 * 注意：
 * 作者（AUTHOR）改成自己
 * 请填写 模块名（MODEL）
 * 请填写 表名（TABLES）
 * </pre>
 *
 * @author yangzj
 */
@SuppressWarnings("all")
public class CodeGenerator {
    public static final String AUTHOR = "yangzj";

    public static final String MODEL = "star";
    public static final String TABLES = "star_ad";

    // 固定值如果表没有字段自然不会填充
    public static final String TABLE_FILLS = "creator,create_time,updater,update_time";/// creator,create_time,updater,update_time
    /// public static final String MODEL_PATH = "/demo-" + MODEL + "/src/main";
    public static final String MODEL_PATH = "/star-apps/target/generated-sources";
    public static final String MODEL_PATH_JAVA = "/java";
    public static final String MODEL_PATH_RESOURCES = "/resources";
    public static final String PARENT = "com.star";

    public static final String URL = "jdbc:mysql://localhost:3306/star?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) {
        String modelName = MODEL.contains("-") ? MODEL.substring(0, MODEL.indexOf("-")) : MODEL;
        /// String modelName = scanner("模块名");
        String projectPath = System.getProperty("user.dir");
        String outputDir = projectPath + MODEL_PATH;
        FastAutoGenerator.create(URL, USERNAME, PASSWORD)
                .globalConfig(builder -> {
                    builder.author(AUTHOR)
                            .disableOpenDir() // 禁止打开输出目录
                            .outputDir(outputDir + MODEL_PATH_JAVA); // 指定输出目录
                })
                .dataSourceConfig(builder -> builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                    int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                    int length = metaInfo.getLength();
                    if (typeCode == Types.TINYINT) {
                        // tinyint转换成Integer
                        return length == 1 ? DbColumnType.BOOLEAN : DbColumnType.INTEGER;
                    }
                    return typeRegistry.getColumnType(metaInfo);
                }))
                .packageConfig(builder -> {
                    builder.parent(PARENT + "." + modelName) // 设置父包名
                            // 设置mapperXml生成路径
                            .pathInfo(Collections.singletonMap(OutputFile.xml, outputDir + MODEL_PATH_RESOURCES + "/mapper/" + modelName));
                })
                .strategyConfig(builder -> {
                    String[] tableNames = TABLES.split(",");
                    // String[] tableNames = scanner("表名，多个英文逗号分割").split(",");
                    Column[] tableFills = null;
                    boolean hasFill = TABLE_FILLS.length() > 0;
                    if(hasFill) {
                        tableFills = Arrays.stream(TABLE_FILLS.split(","))
                                .map(c -> c.startsWith("c") ? new Column(c, FieldFill.INSERT) : new Column(c, FieldFill.INSERT_UPDATE))
                                .toArray(Column[]::new);
                    }
                    builder.addInclude(tableNames)
                            .controllerBuilder().superClass(BaseController.class).enableRestStyle()
                            .serviceBuilder().formatServiceFileName("%sService").formatServiceImplFileName("%sServiceImpl")
                            .entityBuilder().idType(IdType.ASSIGN_ID)
                            .enableLombok().enableChainModel()
                            //.mapperBuilder().enableBaseColumnList()// 启用 BaseColumnList
                            //.logicDeleteColumnName("deleted")
                            ;
                    if(hasFill){
                        builder.entityBuilder().addTableFills(
                                tableFills
                        );
                    }
                    ;

                })
                .templateEngine(new FreemarkerTemplateEngine())
                .execute();
    }

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入" + tip + "：");
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (ipt != null && !ipt.equals("")) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

}
